//网易云信相关引入
import RootStore from '@xkit-yx/im-store'
import appConfig from "@/config/index.js"
import {
	NimKitCore
} from '@xkit-yx/core-kit/dist/uniapp-nim-core'
import {
	getMsgContentTipByType
} from './msg';
import { setTabBarBadge } from './setTabBarBadge'
import {
	computed
} from "vue";

import {
	listPatientLog,
	checkSystem
} from "@/request/apis/im.js";

import {
	useStore
} from '@/store';

// const { NECall } = require('../../static/yunxin/call.js');

export const getUniPlatform = () => {
  return uni.getSystemInfoSync().uniPlatform
}

export const getPlatform = () => {
  return uni.getSystemInfoSync().platform
}
const getPatientMsgNum = () => {
	let num = 0;
	const store = useStore();
	const patient = computed(() => store.patient.current);
	listPatientLog({patientId:patient.value.id}).then((res: any) => {
		for (let i = 0;i<res.length;i++) {
			num += res[i].remind
		}
		getSystemNum(num)
	}).catch(() => {
	});
}
	
const getSystemNum = (num:number) =>{
	const store = useStore();
	const patient = computed(() => store.patient.current);
	checkSystem({patientId:patient.value.id}).then((res: any) => {
		num += res.remind;
		setTabBarBadge(num);
	}).catch(() => {});
}
	
export const updateBadge = (type:number,num = 0) => {
	if (type === 0) {
		getPatientMsgNum()
	} else {
		setTabBarBadge(num);
	}
}
export const initIm = (account:string,token:string,type:number=0) => {
	// 网易云信初始化
	const nim = uni.$UIKitNIM = new NimKitCore({
		initOptions: {
			"appkey": appConfig.im.appKey, //您在云信控制台注册的appkey
			"account": account, //云信控制台上的account
			"token": token, //云信控制台的账号token
			"lbsUrls": [
				"https://lbs.netease.im/lbs/webconf.jsp"
			],
			"linkUrl": "weblink.netease.im",
			"needReconnect": true,
			// "reconnectionAttempts": 5,
			debugLevel: "off"
		},
		platform: 'UniApp',
	})
	uni.$UIKitStore = new RootStore(nim, {
	  addFriendNeedVerify: false,
	  teamBeInviteMode: 'noVerify',
	  teamJoinMode: 'noVerify',
	  teamUpdateExtMode: 'all',
	  teamUpdateTeamMode: 'all',
	  teamInviteMode: 'all',
	  sendMsgBefore: async (options, type) => {
		
		const pushContent = getMsgContentTipByType({ body: options.body, type })
					
		// 如果是 at 消息，需要走离线强推
		const { forcePushIDsList, needForcePush } = options.ext?.yxAitMsg
		  // @ts-ignore
		  ? store.msgStore._formatExtAitToPushInfo(options.ext?.yxAitMsg, options.body)
		  : { forcePushIDsList: '[]', needForcePush: false }
	
		// 不同厂商的推送消息体
		const { scene, to } = options
		const pushPayload = JSON.stringify({
		  // oppo
		  oppoField: {
			"click_action_type": 4, // 参考 oppo 官网
			"click_action_activity": '', // 各端不一样 TODO
			"action_parameters": { "sessionId": scene, "sessionType": to } // 自定义
		  },
	
		  // vivo
		  vivoField: {
			"pushMode": 0 //推送模式 0：正式推送；1：测试推送，不填默认为0
		  },
	
		  // huawei
		  hwField: {
			click_action: {
			  'type': 1,
			  'action': '' // 各端不一样 TODO
			},
			androidConfig: {
			  'category': 'IM',
			  'data': JSON.stringify({ 'sessionId': to, 'sessionType': scene })
			}
		  },
	
		  // 通用
		  sessionId: to,
		  sessionType: scene,
		})
		const pushInfo = {
		  needPush: true,
		  needPushBadge: true,
		  pushPayload: '{}',
		  pushContent,
		  needForcePush,
		  forcePushIDsList,
		  forcePushContent: pushContent,
		}
		return { ...options, pushInfo }
	  },
	})
	nim.on('logined', () => {
		uni.$emit("IM_LOGINED")
	})
	
	nim.on('msg', (msg)=>{
		setTimeout(function() {
			updateBadge(0)
			uni.$emit("newMsg")
		},1000)
		
	})
	nim.connect()
	uni.setStorageSync("yxAccountId",account);
}

export const switchIm = async (account:string,token:string) => {
	if (uni.getStorageSync("yxAccountId") != account) {
		uni.$UIKitStore.destroy()
		uni.$UIKitNIM.disconnect().then(()=>{
			uni.$UIKitNIM.destroy().then(()=>{
				setTimeout(function(){
					initIm(account,token)
				},200)
				
			})
		})
	}
}

export const quitIm =  () => {
	return new Promise(async (resolve, reject) => {
		uni.$UIKitNIM.disconnect()
		uni.$UIKitNIM.destroy()	
		resolve(true)
	});	
}